package cn.openea.perpartner.cms.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.cms.bean.FieldData;
import cn.openea.perpartner.cms.bean.PdfDataSource;
import cn.openea.perpartner.cms.bean.properties.DType;
import cn.openea.perpartner.cms.factory.UserContext;
import cn.openea.perpartner.cms.utils.CosUpload;
import cn.openea.perpartner.cms.utils.PdfModel;
import cn.openea.perpartner.cms.web.dto.CommodityCheck;
import cn.openea.perpartner.cms.web.dto.CommodityDto;
import cn.openea.perpartner.cms.web.dto.CommodityPdf;
import cn.openea.perpartner.cms.web.entity.CmsCommodity;
import cn.openea.perpartner.cms.web.mapper.CmsCommodityMapper;
import cn.openea.perpartner.cms.web.service.ICmsCommodityService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.openea.perpartner.common.core.config.SystemConfig;
import cn.openea.perpartner.common.core.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * (CmsCommodity)表服务实现类
 *
 * @author makejava
 * @since 2022-08-23 12:10:44
 */
@Service("cmsCommodityService")
public class CmsCommodityServiceImpl extends ServiceImpl<CmsCommodityMapper, CmsCommodity> implements ICmsCommodityService {
    @Autowired
    private CosUpload cosUpload;

    @Override
    public List<CmsCommodity> selectList(String customerId) {
        LambdaQueryWrapper<CmsCommodity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmsCommodity::getCustomerId, customerId);
        wrapper.orderByAsc(CmsCommodity::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<CmsCommodity> selectAll(String userId, String searchStr, String commodityStatus) {
        LambdaQueryWrapper<CmsCommodity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(userId)) {
            wrapper.eq(CmsCommodity::getCreateUser, userId);
        }
        if (StrUtil.isNotBlank(commodityStatus)) {
            wrapper.eq(CmsCommodity::getCommodityStatus, commodityStatus);
        }
        if (StrUtil.isNotBlank(searchStr)) {
            wrapper.and(wrap -> wrap.like(CmsCommodity::getCommodityName, searchStr)
                    .or().like(CmsCommodity::getTaobaoPrice, searchStr)
                    .or().like(CmsCommodity::getCommodityNum, searchStr)
                    .or().like(CmsCommodity::getReturnAddress, searchStr)
                    .or().like(CmsCommodity::getCommodityStatus, searchStr)
                    .or().like(CmsCommodity::getPlanTime, searchStr)
                    .or().like(CmsCommodity::getShelfTime, searchStr)
                    .or().like(CmsCommodity::getSupplyPrice, searchStr)
                    .or().like(CmsCommodity::getShopName, searchStr)
                    .or().like(CmsCommodity::getFloorPrice, searchStr)
                    .or().like(CmsCommodity::getChannelPrice, searchStr)
            );
        }
        wrapper.eq(CmsCommodity::getSigningStatus, "2");
        wrapper.orderByDesc(CmsCommodity::getShelfTime);
        wrapper.orderByDesc(CmsCommodity::getCommodityStatus);
        wrapper.orderByDesc(CmsCommodity::getCommodityNum);
        return baseMapper.selectList(wrapper);
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public boolean updateBatch(List<CommodityDto> commodityDtoList) {
        boolean isSuccess = false;
        for (CommodityDto commodityDto : commodityDtoList) {
            CmsCommodity commodity = baseMapper.selectById(commodityDto.getCommodityId());
            if (BeanUtil.isNotEmpty(commodity)) {
                BeanUtil.copyProperties(commodityDto, commodity, BeanUtils.getNullField(commodityDto));
                if (StrUtil.isNotBlank(commodity.getTaobaoPrice()) && StrUtil.isNotBlank(commodity.getChannelPrice())) {
                    commodity.setCommodityStatus("未上架淘宝");
                }
                if (StrUtil.isNotBlank(commodity.getPlanTime())) {
                    commodity.setCommodityStatus("已安排上架");
                }
                if (StrUtil.isNotBlank(commodity.getTaobaoPrice()) && StrUtil.isNotBlank(commodity.getChannelPrice())
                        && StrUtil.isNotBlank(commodity.getPlanTime()) && StrUtil.isNotBlank(commodity.getShelfTime())
                        && StrUtil.isNotBlank(commodity.getReturnAddress()) && StrUtil.isNotBlank(commodity.getCommodityDetail())) {
                    commodity.setCommodityStatus("已上架淘宝");
                }
                commodity.setUpdateUser(UserContext.getUserId());
                isSuccess = updateById(commodity);
            }
        }
        return isSuccess;
    }

    @Override
    public boolean check(String customerId) {
        LambdaQueryWrapper<CmsCommodity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CmsCommodity::getCustomerId, customerId);
        List<CmsCommodity> commodityList = list(wrapper);
        if (commodityList.isEmpty()) {
            return false;
        }
        for (CmsCommodity commodity : commodityList) {
            CommodityCheck commodityCheck = new CommodityCheck();
            BeanUtil.copyProperties(commodity, commodityCheck);
            Map<String, Object> supplementMap = BeanUtil.beanToMap(commodityCheck);
            for (Map.Entry<String, Object> entry : supplementMap.entrySet()) {
                if (ObjectUtil.isEmpty(entry.getValue())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public String preview(List<Long> idList) throws IOException {
        boolean rotate = false;
        String titleText = "最佳拍档产品报价表";
        //List<String> headTag = Arrays.asList("产品名称","图片","规格","一件代发价","备注");
        List<String> headTag = Arrays.asList("商品名称", "商品图", "规格", "供货价", "控价", "渠道供货价");
        List<List<FieldData>> dataList = new ArrayList<>();
        LambdaQueryWrapper<CmsCommodity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CmsCommodity::getCommodityId, idList);
        List<CmsCommodity> commodityList = baseMapper.selectList(wrapper);
        for (CmsCommodity commodity : commodityList) {
            List<FieldData> fieldDataList = new ArrayList<>();
            CommodityPdf commodityPdf = new CommodityPdf();
            BeanUtil.copyProperties(commodity, commodityPdf);
            Map<String, Object> map = BeanUtil.beanToMap(commodityPdf);
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String url = "";
                DType dType = DType.TEXT;//文本显示类型
                if (i == 0) {
                    dType = DType.TEXTURL;//更改为文本A标签类型
                    url = "https://dev.openea.net/";//当 DType.TEXTURL 时，需要补充单击文本转向的地址路径
                } else if (i == 1) {
                    dType = DType.IMAGE;//更改为图片类型
                }
                //住1行表格数据中添加字段信息，包含 字段值、字段类型、字段点击的转向地址（可为空）
                fieldDataList.add(new FieldData(entry.getValue().toString(), dType, url));
                i++;
            }
            dataList.add(fieldDataList);
        }
        //参数5：尾部说明文字，换行请使用\n，不支持\t
        String tailText = "报价说明：\n" +
                "1、报价随时变化，有效期限15天，以本公司最终报价单为准。\n" +
                "2、报价为含运费不含税，开13%增值税专票需另外加10个点，专票最低需满2000元起开票。\n" +
                "3、本报价单解释权归OpenEA最佳拍档平台所有。";
        //参数6：定义使用的字体，default 表示默认宋体，可指定 font="/static/fonts/simyou.ttf" 使用幼圆，如需要加字体，请将字体文件复制到 src/main/resources/static/fonts 目录
        //若在Linux下使用幼圆字体生成的pdf有中文显示问题，请使用 default 更换默认宋体
        String font = "/static/fonts/simyou.ttf";
        // *************** 定义PdfDataSource数据 End ***************
        PdfDataSource pdfDataSource = new PdfDataSource(rotate, titleText, headTag, dataList, tailText, font);
        PdfModel pdfModel = new PdfModel(pdfDataSource);
        String outpath = SystemConfig.getProfile() + "/tmpfiles/";
        File file = new File(outpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        outpath += UserContext.getUserId() + ".pdf";
        pdfModel.createPDF(outpath);
        //第3步，将生成的文件推送到COS存储桶中并提供下载
        File uploadfile = new File(outpath);
        return cosUpload.uploadFile(uploadfile, false);
    }
}

